package org.dawfinn.droiditarian;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dawfinn.droiditarian.server.data.PMF;
import org.dawfinn.droiditarian.proto.Droiditarian;

@SuppressWarnings("serial")
public class DeedListServlet extends HttpServlet {
	private static final String UTF_8 = "UTF-8";
	private static final DateFormat DATE_FORMAT = DateFormat.getInstance();
	private static final String BEFORE_PARAM = "beforeDate";

	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Date beforeDate;
		String dateString = req.getParameter(BEFORE_PARAM);
		if (dateString != null) {
			try {
				beforeDate = DATE_FORMAT
						.parse(URLDecoder.decode(dateString, UTF_8));
			} catch (ParseException e) {
				resp.setContentType("text/html");
				ServletOutputStream outputStream = resp.getOutputStream();
				outputStream.println("Parse error.");
				outputStream.close();
				return;
			}
		} else {
			beforeDate = new Date();
		}

		OutputStream out = resp.getOutputStream();

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query q = pm.newQuery(org.dawfinn.droiditarian.server.data.Deed.class);
		if (beforeDate != null) {
			q.declareParameters("java.util.Date " + BEFORE_PARAM);
			q.setFilter("releaseDate < " + BEFORE_PARAM);
		}
		q.setOrdering("releaseDate desc");
		q.setRange(0, 15);

		List<org.dawfinn.droiditarian.server.data.Deed> results = (List<org.dawfinn.droiditarian.server.data.Deed>) q
				.execute(beforeDate);
		for (org.dawfinn.droiditarian.server.data.Deed deed : results) {
			Droiditarian.Deed.newBuilder().setKey(deed.getWebsafeKey()).setName(
					deed.getName()).setDescription(deed.getDescription())
					.setExplanation(deed.getExplanation()).setMoreInfo(
							deed.getMoreInfo().getValue()).setReleaseDate(
							deed.getReleaseDate().getTime()).build().writeDelimitedTo(
							out);
		}

		pm.close();
		out.close();
	}
}
